package com.dong8.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dong8.R;
import com.dong8.resp.RespUser;
import com.dong8.sys.Constants;
import com.dong8.sys.MyApp;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.PreferencesUtils;
import com.dong8.util.TLog;
import com.dong8.util.ToastUtil;
import com.loopj.android.http.RequestParams;

public class LoginActivity extends Activity implements OnClickListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		((TextView) findViewById(R.id.tv_title)).setText("登录");
		findViewById(R.id.ibBack).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		findViewById(R.id.regist).setOnClickListener(this);
		
		((MyApp)getApplicationContext()).addActivity(this);
	}

	protected void onDestroy()
	{
		super.onDestroy();
		((MyApp)getApplicationContext()).removeActivity(this);
	}
	
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.ibBack:
			finish();
			break;

		case R.id.login:
			getData();
			break;

		case R.id.regist:
			startActivity(new Intent(this, InputTelephoneActivity.class));
			finish();
			break;
		}
	}

	private void getData() {
		final String tel = ((EditText) findViewById(R.id.tel)).getText().toString();
		final String pwd = ((EditText) findViewById(R.id.pwd)).getText().toString();

		if (pwd.length() == 0 || tel.length() == 0) {
			ToastUtil.showToastWithAlertPic("手机号/密码不能为空");
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				super.onSuccess(response);
				
				RespUser respUser = JSON.parseObject(response, RespUser.class);
				if (respUser.code == 0) {
					TLog.i("hansen", "------------"+respUser.data);
					PreferencesUtils.putString(LoginActivity.this,"user", JSON.toJSONString(respUser.data.get(0)));
					ToastUtil.showToastWithOkPic("登录成功");
					finish();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(respUser.mesg);
				}
			}

			public void onFailure(Throwable ble) 
			{
				
			}
		};

		RequestParams params = new RequestParams();
		params.put("username", tel);
		params.put("password", pwd);
		MgqRestClient.get(Constants.USER_LOGIN, params, loginHandler);
	}
}
